package utils

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// WalkDir 递归遍历目录下的所有文件
func WalkDir(filepath string) ([]string, error) {
	files, err := ioutil.ReadDir(filepath) // files为当前目录下的所有文件名称【包括文件夹】
	if err != nil {
		return nil, err
	}

	var allfile []string
	for _, v := range files {
		fullPath := filepath + "/" + v.Name() // 全路径 + 文件名称
		fullPath = strings.ReplaceAll(fullPath, "//", "/")
		if v.IsDir() { // 如果是目录
			a, _ := WalkDir(fullPath) // 遍历改路径下的所有文件
			allfile = append(allfile, a...)
		} else {
			allfile = append(allfile, fullPath) // 如果不是文件夹，就直接追加到路径下
		}
	}

	return allfile, nil
}

func DeleteBlankFile(srcFilePah string) error {
	text := strings.Builder{}
	srcFile, err := os.OpenFile(srcFilePah, os.O_RDONLY, 0666)
	defer srcFile.Close()
	if err != nil {
		return err
	}
	file := bufio.NewReader(srcFile)
	fw, err := os.OpenFile(srcFilePah, os.O_WRONLY|os.O_CREATE, 0666)

	defer fw.Close()
	if err != nil {
		return err

	}

	for {
		str, err := file.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				fmt.Print("The file end is touched.")
				break

			} else {
				return err
			}
		}

		temp := strings.TrimSpace(str)
		if 0 == len(temp) || temp == "\r\n" {
			continue
		}
		text.WriteString(str)
	}

	w := bufio.NewWriter(fw)
	result := text.String()
	_, err = w.WriteString(result)
	CheckErr(err)
	CheckErr(w.Flush())
	return nil
}

func CreateFileWithDir(path string, name string, content string) {
	os.MkdirAll(path, os.ModePerm)
	file, _ := os.OpenFile(path+"/"+name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	defer file.Close()
	file.WriteString(content)
}

// 删除目录下的全部文件
func DeleteDirFile(dirPath string) {
	_, err := os.Stat(dirPath)
	if os.IsNotExist(err) {
		return
	}
	dir, err := ioutil.ReadDir(dirPath)
	CheckErr(err)
	for _, d := range dir {
		os.RemoveAll(path.Join([]string{dirPath, d.Name()}...))
	}
}

// 拷贝目录
func CopyDir(src string, dest string) {
	src_original := src
	CheckErr(os.MkdirAll(dest, 0755))
	err := filepath.Walk(src, func(src string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			//			fmt.Println(f.Name())
			//			copyDir(f.Name(), dest+"/"+f.Name())
		} else {
			//fmt.Println(src)
			//fmt.Println(src_original)
			//fmt.Println(dest)

			dest_new := strings.Replace(src, src_original, dest, -1)
			//fmt.Println(dest_new)
			// fmt.Println("CopyFile:" + src + " to " + dest_new)
			CopyFile(src, dest_new)
		}
		//println(path)
		return nil
	})
	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
}

//egodic directories
func getFilelist(path string) {
	err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		if f.IsDir() {
			return nil
		}
		println(path)
		return nil
	})
	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\n", err)
	}
}
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

//copy file
func CopyFile(src, dst string) (w int64, err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer srcFile.Close()
	// fmt.Println("dst:" + dst)
	dst_slices := strings.Split(dst, "/")
	dst_slices_len := len(dst_slices)
	dest_dir := ""
	for i := 0; i < dst_slices_len-1; i++ {
		dest_dir = dest_dir + dst_slices[i] + "/"
	}
	//dest_dir := getParentDirectory(dst)
	// fmt.Println("dest_dir:" + dest_dir)
	b, err := PathExists(dest_dir)
	if b == false {
		err := os.MkdirAll(dest_dir, os.ModePerm) //在当前目录下生成md目录
		if err != nil {
			fmt.Println(err)
		}
	}
	dstFile, err := os.Create(dst)

	if err != nil {
		fmt.Println(err.Error())
		return
	}

	defer dstFile.Close()

	return io.Copy(dstFile, srcFile)
}
